package com.szxy.cart.service.impl;

import com.szxy.cart.feigin.CommonItemsFeignClient;
import com.szxy.cart.service.CookieCartService;
import com.szxy.pojo.TbItem;
import com.szxy.utils.CartItem;
import com.szxy.utils.CookieUtils;
import com.szxy.utils.JsonUtils;
import com.szxy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther:zwer
 * @Date:2019/9/12 10:13
 * @Description:com.szxy.cart.service.impl
 * @Version:1.0
 **/
@Service
public class CookieCartServiceImpl implements CookieCartService {

    @Value("${cookie_cart_name}")
    private String cookie_cart_name;
    @Autowired
    private CommonItemsFeignClient commonItemsFeignClient;

    @Override
    public Result deleteItemFromCart(Long itemId, HttpServletRequest request, HttpServletResponse response) {
        // 1. 获取当前购物车
        Map<String, CartItem> cart = this.getCurrentCart(request);
        // 2.删除的商品
        cart.remove(itemId.toString());
        // 3. 将更新数据加入 Cookies 中
        this.cartToCookie(cart, request, response);
        // 返回
        return Result.ok();
    }

    @Override
    public Result updateItemNum(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) {
        // 1. 获取当前购物车
        Map<String, CartItem> cart = this.getCurrentCart(request);
        // 2.获取需要更新的商品
        CartItem cartItem = cart.get(itemId.toString());
        if (cartItem != null) {
            cartItem.setNum(num);
            // 3. 将更新数据加入 Cookies 中
            this.cartToCookie(cart, request, response);
        }
        return Result.ok();
    }

    @Override
    public Result showCart(HttpServletRequest request, HttpServletResponse response) {
        Map<String, CartItem> cart = this.getCurrentCart(request);
        List<CartItem> cartItemList = new ArrayList<>();
        for (String key : cart.keySet()) {
            cartItemList.add(cart.get(key));
        }
        return Result.ok(cartItemList);
    }

    @Override
    public Result addItem(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) {
        // 1. 获取当前购物车
        Map<String, CartItem> cart = this.getCurrentCart(request);
        // 2. 获取商品数据
        TbItem item = this.commonItemsFeignClient.findItemById(itemId);
        // 3. 将商品加入到购物车中
        this.addItemToCart(item, num, cart);
        // 4. 将当前购物车放入 Cookie 中保存
        this.cartToCookie(cart, request, response);
        return Result.ok();
    }

    private void cartToCookie(Map<String, CartItem> cart
            , HttpServletRequest request, HttpServletResponse response) {
        String cartJson = JsonUtils.objectToJson(cart);
        CookieUtils.setCookie(request, response, this.cookie_cart_name, cartJson, true);
    }

    private void addItemToCart(TbItem item, Integer num, Map<String, CartItem> cart) {
        CartItem cartItem = null;
        // 判断当前 item.getId() 作为 可以，查到对应的 value 是否存在
        cartItem = cart.get(item.getId().toString());// 注意： item 对象的 id 是 Long 类型，而 Map 对象的 key 是 String 类型
        if (cartItem == null) {
            // 若不存在购物车中，则创建 CartItem 对象加入 Map 集合中
            cartItem = new CartItem();
            cartItem.setId(item.getId());
            cartItem.setTitle(item.getTitle());
            cartItem.setNum(num);
            cartItem.setPrice(item.getPrice());
            cartItem.setSell_point(item.getSellPoint());
            cartItem.setImage(item.getImage());
            cart.put(item.getId().toString(), cartItem);
        } else {
            // 若存在购物车中，则只修改该 cartItem 对象的 num 属性
            cartItem.setNum(cartItem.getNum() + num);
        }
    }

    private Map<String, CartItem> getCurrentCart(HttpServletRequest request) {
        Map<String, CartItem> cart = null;
        try {
            // 获取当前 Cookie 中购物车 Json 数据
            String cartJson = CookieUtils.getCookieValue(request, this.cookie_cart_name, true);
            if (cartJson != null) {
                // 将 cartJson 转为 Map 对象
                cart = JsonUtils.jsonToMap(cartJson, CartItem.class);
                if (cart != null) return cart;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<String, CartItem>();
    }
}
